<template>
  <div class="game-page-view">
  
    <div style="margin: auto;width: 100%;height: 100%;" class="egret-player"
         data-entry-class="Main"
         data-orientation="portrait"
         data-scale-mode="exactFit"
         data-frame-rate="30"
         data-content-width="640"
         data-content-height="1136"
         data-show-paint-rect="false"
         data-multi-fingered="2"
         data-show-fps="false" data-show-log="false"
         data-show-fps-style="x:0,y:0,size:12,textColor:0xffffff,bgAlpha:0.9">
    </div>
  
    <div class="shade-game center-parent" v-show="!gameLoadEnd">

      <img src="./../assets/imgs/loading/img_01.png" class="cloud-1">
      <img src="./../assets/imgs/loading/img_02.png" class="cloud-2">
      <div class="center-child load-view">
        <div class="animal-wait">
          <img src="./../assets/imgs/loading/img_04.png" class="yanhua">
          <img src="./../assets/imgs/loading/img_04.png" class="yanhua2">
          <img src="./../assets/imgs/loading/01.png" class="hua">
          <img src="./../assets/imgs/loading/img_06.png" class="animal">
        </div>
        <div class="process-view">
          <div class="process-bar">
            <div class="precess-bar" :style="barStyle"></div>
            <img src="./../assets/imgs/loading/img_03.png" :style="dengStyle">
          </div>
          <p>Loading...  {{parseInt(precent*100)}}% </p>
        </div>
      </div>
    </div>
    <!-- <div class="daojishi" v-show="gameLoadEnd&&beforeStartCount>0"> -->
    <div class="daojishi-father" v-show="beforeStartTimer&&beforeStartCount>0">
      <div :class="['daojishi', 'animated',beforeStartTimer ? 'zoomIn':'']"  ref="daojishi">
        <div >{{beforeStartCount}}</div>
      </div>
    </div>
    
    <div class="left-result tongji">
      <img src="./../assets/imgs/img_01.png" alt="" :class="catchedAnimate&&gameLeftTime>0?'warn-wave-cash':''" ref="animalAnimate">
      <div>
        已抓：<span>{{catched}}</span><i></i>本关还剩：<span>{{levelLeftAnimals}}</span>
      </div>
    </div>
    <div class="right-time tongji">
      <img src="./../assets/imgs/img_03.png" alt="" :class="gameLeftTime<6&&gameLeftTime>0 ?'warn-wave':''">
      <div>
        <span>{{gameLeftTime}}</span>s
      </div>  
    </div>
    <!-- <vue-alert-loading :visible="sending" text="正在更新成绩"             :title="title"
      :originDivWidth="originDivWidth"
      :originDivHeight="originDivHeight"
      :loadingDivWidth="loadingDivWidth"
    /> -->
    <Dialog :visible.sync="visible">
      <div slot="content" >
        <catch-result v-if="visibleType=='CatchResult'"
          @close="closeDialog"
          @openOther="changeDialogType"
          @share="openShare"
        ></catch-result>
        <best-result v-if="visibleType=='BestResult'"
          @close="closeDialog"
          @share="openShare"
          @openOther="changeDialogType"
        ></best-result>
        <Lotto v-if="visibleType=='Lotto'"
          @close="closeDialog"
          @openOther="changeDialogType"
        ></Lotto>
        <no-award v-if="visibleType=='NoAward'" @close="closeDialog"></no-award>
        <get-award v-if="visibleType=='GetAward'"  @close="closeDialog"></get-award>
        <end-award v-if="visibleType=='EndAward'" @close="closeDialog" @share="openShare"></end-award>
      </div>   
    </Dialog>

    <Dialog :visible.sync="isNew">
      <div slot="content" >
        <lead-new @close="closeNew"></lead-new>
      </div>
    </Dialog>
    <Dialog :visible.sync="shareVisible" @click.native="shareVisible=false">
      <div slot="content" >
        <Share></Share>
      </div>
    </Dialog>
  </div>
</template>
<script>
  import Dialog from './../components/dialog.vue'
  import CatchResult from './../components/catch-result.vue'
  import BestResult from './../components/best-result.vue'
  import Lotto from './../components/lotto.vue'
  import NoAward from './../components/no-award.vue'
  import GetAward from './../components/get-award.vue'
  import Share from './../components/share.vue'
  import EndAward from './../components/end.vue'
  import LeadNew from './../components/lead-new.vue'
  import Utils from './../utils.js'
  import { Indicator } from 'mint-ui'

  export default {
    name: "Game",
    components:{
      Dialog,
      CatchResult,
      BestResult,
      Lotto,
      NoAward,
      GetAward,
      Share,
      EndAward,
      LeadNew
    },
    data() {
      return {
        limitTime:45,// 游戏时长
        hasRunTime:0,
        timer:null,
        catched:0,
        visible:false,
        visibleType:'',
        shareVisible:false,
        loadingDivWidth:120,
        title:'',
        originDivHeight:20,
        originDivWidth:20,
        levelLeftAnimals:1,
        beforeStartTimer:false,
        beforeStartCount:3,
        catchedAnimate:false,
        isNew:false, //新手
      };
    },
    computed: {
      precent(){
        return this.$store.getters.loadPrecess
      },
      gameLoadEnd(){
        return this.$store.getters.gameLoadEnd
      },
      barStyle(){
        return {
          width: this.precent*100+'%'
        }
      },
      dengStyle(){
        return {
          left: (this.precent*100-10)+'%'
        }
      },
      gameLeftTime(){
        return this.limitTime - this.hasRunTime
      },
  
    },
    watch:{
      gameLoadEnd:function(val){
        if(val){
          this.isNew = true
          this.ReStartGame()
        }
      }
    },
  
    mounted() {   
      let vm = this  
      this.$store.dispatch('getFriendsList')
      this.initGame()
      this.$refs.animalAnimate.addEventListener('webkitAnimationEnd',vm.animalAnimate,false)
    },
    deactivated(){
      this.visible = false
      this.shareVisible = false
      if(this.timer){
        clearInterval(this.timer)
        this.timer = null
      }
    },
    activated(){
      // if(this.beforeStartTimer){
      //   clearInterval(this.beforeStartTimer)
      //   this.beforeStartTimer = null
      // }
      if(this.gameLoadEnd){
        this.ReStartGame()
      }
      
    },  
    methods: {
      closeNew(){
        this.isNew = false
        this.beforeStartTimer = true
      },
      animalAnimate(){
        this.catchedAnimate = false
      },
      daojishiStart(){

      },
      daojishiIteration(){
        this.beforeStartCount --
        if(this.beforeStartCount==0){
          this.startTimer()
        }
      },
      daojishiEnd(){
        
      },
      ReStartGame(){
        console.log('重新开始游戏')
        this.levelLeftAnimals = 1
        this.catched = 0
        this.hasRunTime = 0
        this.beforeStartCount = 3
        NianShouGame.Game.Instance().ReStartGame()
        
        if(this.isNew){ //新手

        }else{
          this.beforeStartTimer = true
        }
        //this.$refs.daojishi.addEventListener('webkitAnimationStart',this.daojishiStart,false)
        this.$refs.daojishi.addEventListener('webkitAnimationIteration',this.daojishiIteration,false)
        //this.$refs.daojishi.addEventListener('webkitAnimationEnd',this.daojishiEnd,false)
        
        // this.beforeStartTimer = setInterval(()=>{
        //   // 3 2 1   
        //   if( this.beforeStartCount ==0){
        //     clearInterval(this.beforeStartTimer)
        //     this.beforeStartTimer = null
        //     this.startTimer()
        //   }else{
        //     this.beforeStartCount--
        //   }      
        // },1000)
        
      },
      startTimer(){
        this.timer = setInterval(()=>{
          if( this.hasRunTime>this.limitTime-1 ){  
            this.timerEnd()
          }else{
            this.hasRunTime++
          }
        },1000)
      },
      timerEnd(){
        let vm = this  
        if(this.timer){
          clearInterval(this.timer)
          this.timer = null
        }
        
        // this.$store.dispatch('addGameTime')
        let str = 'CatchResult'
        if(this.catched > this.$store.state.bestAnimals){//最佳纪录诞生
          str = 'BestResult'
        }
        Indicator.open({
          text: '正在更新成绩...',
          spinnerType: 'fading-circle'
        })
        this.$store.commit('updateAnimals',this.catched)
        this.$store.dispatch('updateBestAnimals').then(()=>{
          this.$store.dispatch('getFriendsList').then(()=>{
            Indicator.close()
            wx.ready(()=>{
              wx.onMenuShareTimeline(vm.$store.getters.wxShareData)
              wx.onMenuShareAppMessage(vm.$store.getters.wxShareData)
            }) 
            this.visible = true
            this.visibleType = str
          }).catch(()=>{
            Indicator.close()
            this.$router.push('/')
          })
        }).catch(()=>{
          Indicator.close()
          this.$router.push('/')
        })
        
      },
      initGame() {
  
        let vm = this
        loadingPrecent = function (data) {
          //定义loading
          console.log(11,data)
          vm.$store.commit('updateGameAssetsLoading',data)
        }
        catchCallback = function (data) {
          //返回击中年兽结果
          // {
          //   isHited:true,
          //   level:3,
          //   levelAnimals:3,
          //   levelLeftAnimals:1
          // }
          console.log(11,data)

          if(data.isHited){
            // 动效
            vm.catchedAnimate = true
            vm.catched ++
          }
          vm.levelLeftAnimals = data.levelLeftAnimals
        }
  
        var loadScript = function(list, callback) {
  
          var loaded = 0;
  
          var loadNext = function() {
  
            loadSingleScript(list[loaded], function() {
  
              loaded++;
  
              if (loaded >= list.length) {
  
                callback();
  
              } else {
  
                loadNext();
  
              }
  
            })
  
          };
  
          loadNext();
  
        };
  
  
  
        var loadSingleScript = function(src, callback) {
  
          var s = document.createElement('script');
  
          s.async = false;
  
          s.src = gameConfig.localPath + src;
  
          s.addEventListener('load', function() {
  
            s.parentNode.removeChild(s);
  
            //s.removeEventListener('load', arguments.callee, false);
  
            callback();
  
          }, false);
  
          document.body.appendChild(s);
  
        };
  
  
  
        var xhr = new XMLHttpRequest();
  
        xhr.open('GET', gameConfig.localPath + 'manifest.json?v=' + Math.random(), true);
  
        xhr.addEventListener("load", function() {
  
          var manifest = JSON.parse(xhr.response);
  
          var list = manifest.initial.concat(manifest.game);
  
          loadScript(list, function() {
  
            /**
  
             * {
  
             * "renderMode":, //Engine rendering mode, "canvas" or "webgl"
  
             * "audioType": 0 //Use the audio type, 0: default, 2: web audio, 3: audio
  
             * "antialias": //Whether the anti-aliasing is enabled in WebGL mode, true: on, false: off, defaults to false
  
             * "calculateCanvasScaleFactor": //a function return canvas scale factor
  
             * }
  
             **/
  
            egret.runEgret({
  
              renderMode: "webgl",
  
              audioType: 0,
  
              calculateCanvasScaleFactor: function(context) {
  
                var backingStore = context.backingStorePixelRatio ||
  
                  context.webkitBackingStorePixelRatio ||
  
                  context.mozBackingStorePixelRatio ||
  
                  context.msBackingStorePixelRatio ||
  
                  context.oBackingStorePixelRatio ||
  
                  context.backingStorePixelRatio || 1;
  
                return (window.devicePixelRatio || 1) / backingStore;
  
              }
  
            });
  
          });
  
        });
  
        xhr.send(null);
  
      },
      resetGame(){
        this.$router.push({
          path:'/start'
        })
      },
      closeDialog(){
        this.visible = false
        if(this.timer){
          clearInterval(this.timer)
          this.timer = null
        }
        //this.ReStartGame()
      },
      changeDialogType(type){
        this.visible = true
        this.visibleType = type
      },
      openShare(){
        this.shareVisible = true
      },
    },

  }
</script>
<style lang="scss" scoped>
  @import './../styles/common';
  
  .game-page-view {
  
    position: relative;
  
    width: 100%;
  
    height: 100%;
    padding: 0;
    margin: 0;
    background-color: #fff;
    .egret-player{
      // width: 100%;
      // height: 100%;
      margin: 0;
      padding: 0;
      position:absolute;
      top:0;
      left:0;
      canvas{
        width:100%;
        height:100%;
      }
    }
    .shade-game {
      z-index: 3;
      position: absolute;
  
      top: 0;
  
      left: 0;
  
      width: 100%;
  
      height: 100%;
      text-align: center;
      background-image: url('./../assets/imgs/loading/bg.jpg');
      @include bg-img();
      .cloud-1{
        position: absolute;
        top:px2rem(108);
        left:0;
        width:px2rem(170);
      }
      .cloud-2{
        position: absolute;
        bottom:px2rem(120);
        right:0;
        width:px2rem(108);
      }
      .load-view{
        width:80%;
        .animal-wait{
          //height: px2rem(500);
          .yanhua{
            position: absolute;
            width: px2rem(120);
            height:  px2rem(120);
            left:px2rem(80);
            top:px2rem(-80);
          }
          .yanhua2{
            position: absolute;
            width: px2rem(120);
            height:  px2rem(120);
            right:px2rem(80);
            top:px2rem(20);
            transform: scale(.6);
          }
          .hua{
            position: absolute;
            right:px2rem(-30);
            top:px2rem(-260);
            width: px2rem(381);
            height:  px2rem(247);
          }
          .animal{
            height: px2rem(158);
          }
        }
        .process-view{
          padding-top: px2rem(92);
          color: $color-1;
          .process-bar{
            margin: 0 auto;
            width:60%;
            height: px2rem(24);
            background-color: #f4c7aa;
            border-radius: px2rem(20);
            position: relative;
            div{
              position: absolute;
              background-color: $color-1;
              height: 100%;
              border-radius: px2rem(20);
              //transition: all .8s;
            }
            img{
              position: absolute;
              height: px2rem(100);
              top:px2rem(-20);
              //transition: all .8s;
            }
          }
          p{
            padding-top: px2rem(30);
            font-weight: bold;
          }
        }
      }
    }
    .daojishi-father{
      z-index: 3;
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      // background-color:green;
    }
    .daojishi{
      // background-color:red;
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      animation-iteration-count: infinite;
      div{
        @extend .center-child;
        background-image: url('./../assets/imgs/times-1.png');
        @include bg-img();
        width:px2rem(284);
        height: px2rem(284);
        text-align: center;
        line-height: px2rem(284);
        font-size: px2rem(240);
        color: #fc6554;
      }

    }
    $font-normal:32px;
    $font-big:42px;
    .tongji{
      position: absolute;
      z-index: 2;
      div{
        background-image: url('./../assets/imgs/img_02.png');
        height: px2rem(72);  
        @include bg-img();
        font-size: px2rem(26);
        padding-right: px2rem(40);
        padding-left: px2rem(80);
        line-height: px2rem(68);
        margin-top: px2rem(20);
        span{
          font-size: px2rem(32);
          margin-left:px2rem(10);
        }
        i{
          margin:0 px2rem(8);
        }
      }
      img{
        position: absolute;
        left:px2rem(-20);
        width:px2rem(92);
        height: px2rem(103);
      }
      &.left-result{
        top: px2rem(20);
        left: px2rem(30);
      }
      &.right-time{
        top: px2rem(20);
        right: px2rem(16);
        width:px2rem(160);
        box-sizing:border-box;
        text-indent: px2rem(10);
        span{
          margin-left: 0;
        }
      }
      
    }
    
  
  }
</style>